package net.vinote.smart.platform.service.handler;

import java.sql.SQLException;

import net.vinote.smart.platform.module.database.DBManager;
import net.vinote.smart.platform.module.database.DBManagerFactory;
import net.vinote.smart.platform.module.database.DBTransaction;
import net.vinote.smart.platform.module.database.bo.BizObject;
import net.vinote.smart.platform.service.SRE;
import net.vinote.smart.platform.service.dw.DataWindow;
import net.vinote.smart.platform.service.dw.handler.CommonHandler;
import net.vinote.smart.platform.service.dw.handler.HandlerPerimissionAnnotation;
import net.vinote.smart.platform.service.util.Permission;
import net.vinote.smart.platform.service.util.Permission.PermissionEnum;

@HandlerPerimissionAnnotation(
		insert = @Permission(PermissionEnum.SMART_DW_CATALOG_INSERT),
		update = @Permission(PermissionEnum.SMART_DW_CATALOG_UPDATE),
		delete = @Permission(PermissionEnum.SMART_DW_CATALOG_DELETE),
		query = @Permission(PermissionEnum.SMART_DW_CATALOG_QUERY))
public class DataWindowCatalogHandler extends CommonHandler {
	@Override
	public void initDisplayForEdit(BizObject bo) {
		setReadOnly("DONO", true);
	}

	@Override
	protected boolean validityCheck(BizObject bo, boolean isInsert) {
		String doNo = bo.getAttribute("DoNo");
		if (doNo == null || "".equals(doNo)) {
			this.error = "模板编号未指定;";
		}

		String doName = bo.getAttribute("DoName");
		if (doName == null || "".equals(doName.trim())) {
			this.error += "模板名称不能为空;";
		}

		String mainTable = bo.getAttribute("MainTable");
		if (mainTable == null || "".equals(mainTable)) {
			this.error += "未指定主表;";
		} else if (!DataWindow.VIRTUAL_FLAG.equalsIgnoreCase(mainTable)
				&& SRE.getTable(mainTable) == null) {
			this.error += mainTable + "表不存在;";
		}
		return error.length() == 0;
	}

	@Override
	protected void beforeDelete(BizObject bo, DBTransaction tx)
			throws SQLException {
		String doNo = bo.getAttribute("DoNo");
		DBManager bm = null;
		// -------第一步:删除dataobject_event记录----
		bm = DBManagerFactory.getInstance("dataobject_event");
		tx.join(bm);
		bm.deleteWhereSql("doNo=?", doNo);
		// -------第二步:删除dataobject_library记录----
		bm = DBManagerFactory.getInstance("dataobject_library");
		tx.join(bm);
		bm.deleteWhereSql("doNo=?", doNo);
	}

}
